package com.wq.io;

import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Author: wangqiang20995
 * @Date:2019/8/16
 * @Description:
 * @Resource:
 */
public class MappedByteBufferDemo {

    public static void main(String[] args){
//        String path = MappedByteBufferDemo.class.getResource("/META-INF/spi/com.wq.spi.Service").getPath();
        String path = "D:\\SFTP\\upload\\016083000083883_20100514_3010_045.txt";
        Path local = Paths.get(path);

        try(FileChannel fileChannel = FileChannel.open(local)){
            MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY,0,fileChannel.size());

            CharBuffer charBuffer = null;
            if(buffer != null){
                charBuffer = Charset.forName("UTF-8").decode(buffer);
            }

            if (charBuffer != null){
                System.out.println(charBuffer.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String write = "D:/SFTP/upload/MappedByteBufferWrite.txt";
        Path writePath = Paths.get(write);
        try(FileChannel writeChannel = FileChannel.open(writePath,StandardOpenOption.CREATE,
                StandardOpenOption.READ,StandardOpenOption.WRITE,
                StandardOpenOption.TRUNCATE_EXISTING)){
            CharBuffer charBuffer = CharBuffer.wrap("HelloWorld MappedByteBuffer");

            MappedByteBuffer buffer = writeChannel.map(FileChannel.MapMode.READ_WRITE,0,1024);

            if (buffer != null){
                buffer.put(Charset.forName("UTF-8").encode(charBuffer));
                System.out.println("done");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}